package com.zhanghang.vending_machine.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhanghang.vending_machine.common.result.PageResult;
import com.zhanghang.vending_machine.common.result.Result;
import com.zhanghang.vending_machine.domain.dto.GoodDto;
import com.zhanghang.vending_machine.domain.po.Good;
import com.zhanghang.vending_machine.domain.vo.GoodVo;
import com.zhanghang.vending_machine.service.GoodService;
import com.zhanghang.vending_machine.mapper.GoodMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author ASUS
* @description 针对表【good】的数据库操作Service实现
* @createDate 2024-11-05 18:10:48
*/
@Service
@Slf4j
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good>
    implements GoodService{

    /**
     * 新增商品
     * @param goodDto
     */
    @Override
    public void addGood(GoodDto goodDto) {
        //拷贝Dto属性
        Good good = new Good();
        BeanUtils.copyProperties(goodDto,good);

        //添加剩余属性创建时间和修改时间
        good.setCreateTime(LocalDateTime.now());
        good.setUpdateTime(LocalDateTime.now());

        //添加商品
        save(good);

    }

    /**
     * 条件分页查询
     * @param categoryId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PageResult PageByCategory(Long categoryId, Long pageNo, Long pageSize) {
        //设置分页条件
        Page<Good> page = Page.of(pageNo, pageSize);

        //设置排序规则
//        page.addOrder(new OrderItem("create_time",false));

        Page<Good> p = lambdaQuery()
                .eq(categoryId != null,Good::getCategoryId,categoryId)
                .page(page);

        //封装分页结果
        PageResult pageResult = new PageResult();

        pageResult.setTotal(p.getTotal());
//        pageResult.setRecords(p.getRecords());
        List<GoodVo> goodVoList =  BeanUtil.copyToList(p.getRecords(),GoodVo.class);
        pageResult.setRecords(goodVoList);
        return pageResult;
    }
    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @Override
    public GoodVo getGoodById(Long id) {
        Good good = getById(id);

        GoodVo goodVo = new GoodVo();
        if (good == null){
            throw new RuntimeException("商品信息异常");
        }
            BeanUtils.copyProperties(good,goodVo);
            return goodVo;
    }
}




